import React from "react";
import "../css/login.css"
import {useNavigate} from 'react-router-dom'
import axios from 'axios'
import setAuthToken from "../utils/setAuthToken";

const Login = (props)=>{
    const navigate = useNavigate();
    const [username, setUsername] = React.useState('');
    const [password, setPassword] = React.useState('');

    const handleUsernameChange = (e) => {
        setUsername(e.target.value);
    };
    
    const handlePasswordChange = (e) => {
        setPassword(e.target.value);
    };

    function handleLogin(){
        axios({
            method:'get',
            url:'http://localhost:5052/api/user/trader/login',
            params:{
                usernameOrEmail:username,
                password:password
            },
            headers: {'Content-Type':'application/x-www-form-urlencoded'}
        }).then(res=>{
            sessionStorage.setItem("token", res.data.data.token); //将token保存到sessionStorage
            setAuthToken(res.data.data.token);  //将token设置到header中
            navigate('/home')
            console.log("请求成功",res.data)
        }).catch(err=>{
            console.log("请求失败",err);
        })
    };


    return (
        <div className="box">
            <div className="forms">
                <div className="tips">
                    <span className="login-btn">login</span>
                </div>
                <div className="login">
                    <div className="form-title">
                        <h1>Trading System</h1>
                    </div>
                    <div className="form">
                        <div className="username input-item">
                            <input type="text" className="ipts" onChange={handleUsernameChange}/>
                        </div>
                        <div className="password input-item">
                            <input type="password" className="ipts" onChange={handlePasswordChange}/>
                        </div>
                        <button className="btn" onClick={handleLogin}>Login</button>
                    </div>
                </div>
            </div>
        </div>
        
    )
}

export default Login